import 'dart:async';
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanchong/conf.dart';
import 'package:wanchong/utils/event_bus.dart';

class ConnectWidget extends StatefulWidget {
  @override
  _ConnectState createState() => _ConnectState();
}

class _ConnectState extends State<ConnectWidget> {
  // eventBus.emit();
  var startWife = 0;
  ConnectivityResult _connectivityResult = ConnectivityResult.none;
  Stream<ConnectivityResult> connectChangeListener() async* {
    final Connectivity connectivity = Connectivity();
    ConnectivityResult previousResult = await connectivity.checkConnectivity();
    yield previousResult;
    await for (ConnectivityResult result
        in connectivity.onConnectivityChanged) {
      if (result != previousResult) {
        yield result;
        previousResult = result;
      }
    }
  }

  StreamSubscription<ConnectivityResult> connectivitySubscription;

  @override
  void initState() {
    super.initState();
    connectivitySubscription = connectChangeListener().listen(
      (ConnectivityResult connectivityResult) {
        if (!mounted) {
          return;
        }
        setState(() {
          _connectivityResult = connectivityResult;
        });
      },
    );
  }

  @override
  void dispose() {
    connectivitySubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    print("----- 网络状态---" + _connectivityResult.toString());
    if (_connectivityResult == ConnectivityResult.wifi) {
      eventBus.emit(NetState, ConnectivityResult.wifi);
      return Container(
        alignment: Alignment.center,
        // child: Text(
        //   '当前为WIFE',
        //   style: TextStyle(color: Colors.red, fontSize: 30.0),
        // ),
      );
    } else if (_connectivityResult == ConnectivityResult.mobile) {
      eventBus.emit(NetState, ConnectivityResult.mobile);

      return Container(
        width: ScreenUtil.getInstance().setSp(150.0),
        alignment: Alignment.center,
        // child: Text(
        //   '当前为移动数据,点击视频可继续播放',
        //   style: TextStyle(
        //     color: Colors.red,
        //     fontSize: 15.0,
        //   ),
        // ),
      );
    } else {
      eventBus.emit(NetState, ConnectivityResult.none);

      return Container(
        alignment: Alignment.center,
        child: Text(
          '当前无网络可用',
          style: TextStyle(color: Colors.red, fontSize: 15.0),
        ),
      );
    }
  }
}
